package com.company.todolist;

import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class TodoList extends Activity {
	
	private static final int ADD_NEW_TODO = Menu.FIRST;
	private static final int REMOVE_TODO = Menu.FIRST+1;
	
	private static final String TEXT_ENTRY_KEY = "TEXT_ENTRY_KEY";
	private static final String ADDING_ITEM_KEY = "ADDING_ITEM_KEY";
	private static final String SELECTED_INDEX_KEY = "SELECTED_INDEX_KEY";
	
	private EditText todoEdit;
	private ListView todoList;	
	private ArrayList<ToDoItem> todoArray;
	private ToDoItemAdapter aa;

	private boolean addingNew = false;
	private ToDoDBAdapter toDoDBAdapter;
	
	private Cursor toDoListCursor;	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
// ======================= start method tracing ======================= //
//        Debug.startMethodTracing("ToDoListTrace");
// ==================================================================== //
        setContentView(R.layout.main);
        
        todoEdit = (EditText) findViewById(R.id.todo_Edit);
        todoList = (ListView) findViewById(R.id.todo_list);        
        
        todoArray = new ArrayList<ToDoItem>();
        aa = new ToDoItemAdapter(this, R.layout.todoview, todoArray);
        todoList.setAdapter(aa);
        
        todoEdit.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(event.getAction() == KeyEvent.ACTION_DOWN)
					if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
						ToDoItem newItem = new ToDoItem(todoEdit.getText().toString());
						toDoDBAdapter.inserTask(newItem);
						updateArray();
						todoEdit.setText("");
						aa.notifyDataSetChanged();						
						cancelAdd();
						return true;
					}				
				return false;
			}
		});          
        
        registerForContextMenu(todoList); 
        restoreUIState();
        
        toDoDBAdapter = new ToDoDBAdapter(this);
        
        toDoDBAdapter.open();
        
        populateTodoList();
    }
    
    private void populateTodoList() {
    	toDoListCursor = toDoDBAdapter.getAllToDoItemsCursor();
    	startManagingCursor(toDoListCursor);
    	updateArray();    	
	}

	private void updateArray() {
		toDoListCursor.requery();
		todoArray.clear();
		
		if(toDoListCursor.moveToFirst())
			do{
				String task = toDoListCursor.getString(ToDoDBAdapter.TASK_COLUMN);
				long created = toDoListCursor.getLong(ToDoDBAdapter.CREATION_DATE_COLUMN);
				ToDoItem newItem = new ToDoItem(task, new Date(created));
				todoArray.add(0, newItem);
				
			}while(toDoListCursor.moveToNext());
			aa.notifyDataSetChanged();
		
	}

	@Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    	int pos = -1;
    	if(savedInstanceState != null)
    		if(savedInstanceState.containsKey(SELECTED_INDEX_KEY))
    			pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1);
    	
    	todoList.setSelection(pos);    
    }
    
    private void restoreUIState() {
    	SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);
    	
    	String text = settings.getString(TEXT_ENTRY_KEY, "");
    	boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false);
    	
    	if(adding){
    		addNewItem();
    		todoEdit.setText(text);
    	}
	}

	@Override
    protected void onPause() {    	
    	super.onPause();
    	
    	SharedPreferences uiState = getPreferences(0);
    	SharedPreferences.Editor editor = uiState.edit();
    	
    	editor.putString(TEXT_ENTRY_KEY, todoEdit.getText().toString());
    	editor.putBoolean(ADDING_ITEM_KEY, addingNew);
    	
    	editor.commit();
    }
	
	@Override
	protected void onDestroy() {
		toDoDBAdapter.close();
// ======================= stop method tracing ======================= //
//        Debug.stopMethodTracing();
// =================================================================== //
		super.onDestroy();	
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(SELECTED_INDEX_KEY, todoList.getSelectedItemPosition());
		super.onSaveInstanceState(outState);
	}
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
    		ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	menu.setHeaderTitle("Selected ToDo");
    	menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove_item);
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	super.onPrepareOptionsMenu(menu);
    	
    	int idx = todoList.getSelectedItemPosition();
    	
    	String removeTitle = getString(addingNew ? R.string.cancel : R.string.remove_item);
    	
    	MenuItem removeItem = menu.findItem(REMOVE_TODO);
    	removeItem.setTitle(removeTitle);
    	removeItem.setIcon(R.drawable.remove_item);
    	removeItem.setVisible(addingNew || idx > 1);
    	    	
    	return true;
    }        
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	super.onOptionsItemSelected(item);
    	int index = todoList.getSelectedItemPosition();
    	switch(item.getItemId()){
    	case(REMOVE_TODO):{
    		if(addingNew){
    			cancelAdd();
    		}else{
    			removeItem(index);
    		}
    		return true;
    	}
    	case(ADD_NEW_TODO):{
    		addNewItem();
        	return true;
    	}
    		
    	}
    	return false;
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	super.onContextItemSelected(item);
    	switch(item.getItemId()){
    	case(REMOVE_TODO):{
    		AdapterView.AdapterContextMenuInfo menuInfo;
    		menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
    		int index = menuInfo.position;
    		
    		removeItem(index);
    		return true;
    	}
    	}
    	return false;
    }
    
    
    private void addNewItem() {
    	addingNew = true;
    	todoEdit.setVisibility(View.VISIBLE);
    	todoEdit.requestFocus();
		
	}

	private void removeItem(int index) {
		toDoDBAdapter.removeTask(index);
		updateArray();
	}

	private void cancelAdd() {
		addingNew = false;
		todoEdit.setVisibility(View.GONE);
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	
    	MenuItem itemAdd = menu.add(0, ADD_NEW_TODO, Menu.NONE, R.string.add_new_item);
    	MenuItem itemRem = menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove_item);
    	
    	itemAdd.setIcon(R.drawable.add_new_item);
    	itemRem.setIcon(R.drawable.remove_item);    	    	
    	
    	return true;
    	
    }
}